<?php
// @formatter:off
/**
 * @file ct.autotag.updateFEWTAGS.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-22 17:58:11 +0000 (Sat, 22 Jun 2013) $
 *
 * $Id: ct.autotag.updateFEWTAGS.php 83 2013-06-22 17:58:11Z daemonraco@gmail.com $
 * $URL: https://wcomix.googlecode.com/svn/trunk/cron/ct.autotag.updateFEWTAGS.php$
 */

$wcCronScripts["autotag.updateFEWTAGS"] = array(
	"auto"		=> true,
	"enabled"	=> true,
	"name"		=> "FEWTAGS entries update",
	"class"		=> "WCTagsUpdateFEWTAGS",
	"url"		=> "http://code.google.com/p/wcomix/"
);
// @formatter:on

/**
 * Defaults
 */
if(!isset($wcDefaults["class-WCTagsUpdateFEWTAGS"])) {
	$wcDefaults["class-WCTagsUpdateFEWTAGS"] = array();
}
if(!isset($wcDefaults["class-WCTagsUpdateFEWTAGS"]["limit"])) {
	$wcDefaults["class-WCTagsUpdateFEWTAGS"]["limit"] = 5;
}
if(!isset($wcDefaults["class-WCTagsUpdateFEWTAGS"]["group-limits"])) {
	$wcDefaults["class-WCTagsUpdateFEWTAGS"]["group-limits"] = array();
}

class WCTagsUpdateFEWTAGS extends WCCronTool {
	public static $TagName = WC_SPECIAL_TAG_FEW_TAGS;

	public function run($spacer = "") {
		global $wcTagsHolder;
		global $wcSpecialTags;
		global $wcGroupsHolder;
		global $wcDefaults;
		global $wcDatabaseAccess;

		$db = WCConnection::Instance();
		$dbPrefix = $wcDatabaseAccess["prefix"];

		foreach($wcGroupsHolder->groups() as $group) {
			if(is_readable($group->root)) {
				$limit = isset($wcDefaults["class-WCTagsUpdateFEWTAGS"]["group-limits"][$group->id]) ? $wcDefaults["class-WCTagsUpdateFEWTAGS"]["group-limits"][$group->id] : $wcDefaults["class-WCTagsUpdateFEWTAGS"]["limit"];

				echo "{$spacer}Checking group '{$group->name}' ({$group->id}) with a limit of {$limit} tags:\n";

				$noTag = $wcTagsHolder->itemByName(WCTagsUpdateNOTAG::$TagName, $group);
				if(!$noTag) {
					$msg = __CLASS__."::".__FUNCTION__."(): Tag '".WCTagsUpdateNOTAG::$TagName."' is not yet present, process will abort.";
					trigger_error($msg, E_USER_ERROR);
				} else {
					$tag = $wcTagsHolder->itemByName(WCTagsUpdateFEWTAGS::$TagName, $group);
					if(!$tag) {
						$wcTagsHolder->create(WCTagsUpdateFEWTAGS::$TagName, $group);
						$tag = $wcTagsHolder->itemByName(WCTagsUpdateFEWTAGS::$TagName, $group);
					}

					//
					// Removing tagged comics
					$stmt = null;
					$stmtId = __CLASS__."::".__FUNCTION__."[rselect]";
					if($db->has($stmtId)) {
						$stmt = $db->get($stmtId);
					} else {
						$query = "select  mem_comic,\n";
						$query .= "        (count(*)-1) as mem_count,\n";
						$query .= "        min(mem_tag) as mem_tag\n";
						$query .= "from    {$dbPrefix}tag_members\n";
						$query .= "                inner join {$dbPrefix}comics\n";
						$query .= "                        on(mem_comic = cmc_id and mem_group = cmc_group)\n";
						$query .= "where   mem_comic in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    {$dbPrefix}tag_members\n";
						$query .= "                where   mem_tag   = :tag\n";
						$query .= "                 and    mem_group = :group)\n";
						$query .= " and    mem_group = :group\n";
						$query .= "group by mem_comic\n";
						$stmt = $db->prepare($stmtId, $query);
					}

					$params = array(
						":group" => $group->id,
						":tag" => $tag->id
					);

					if($stmt->execute($params) && $stmt->rowCount() > 0) {
						foreach($stmt->fetchAll() as $row) {
							if($row["mem_count"] > $limit || $row["mem_count"] == 0) {
								global $wcComicsHolder;

								$comic = $wcComicsHolder->item($row["mem_comic"], $group);
								if($comic && $comic->ok()) {
									echo "{$spacer}\tRemoving '{$comic->name}' ({$comic->id}@{$comic->directory}) from '{$tag->name}'\n";
									$tag->removeComic($comic);
								}
							}
						}
					}

					//
					// Adding tag
					$stmt = null;
					$stmtId = __CLASS__."::".__FUNCTION__."[add]";
					if($db->has($stmtId)) {
						$stmt = $db->get($stmtId);
					} else {
						$query = "select  mem_comic,\n";
						$query .= "        count(*) as mem_count\n";
						$query .= "from    {$dbPrefix}tag_members\n";
						$query .= "                inner join {$dbPrefix}comics\n";
						$query .= "                        on(mem_comic = cmc_id and mem_group = cmc_group)\n";
						$query .= "where   mem_comic not in (\n";
						$query .= "                select  mem_comic\n";
						$query .= "                from    {$dbPrefix}tag_members\n";
						$query .= "                where   mem_group = :group\n";
						$query .= "                 and    mem_tag in (:tag, :notag))\n";
						$query .= " and    mem_group = :group\n";
						$query .= "group by mem_comic\n";
						$stmt = $db->prepare($stmtId, $query);
					}

					$params = array(
						":group" => $group->id,
						":tag" => $tag->id,
						":notag" => $noTag->id
					);

					if($stmt->execute($params)) {
						foreach($stmt->fetchAll() as $row) {
							if($row["mem_count"] <= $limit) {
								global $wcComicsHolder;

								$comic = $wcComicsHolder->item($row["mem_comic"], $group);
								if($comic && $comic->ok()) {
									echo "{$spacer}\tAdding '{$comic->name}' ({$comic->id}@{$comic->directory}) to '{$tag->name}'\n";
									$tag->add($comic);
								}
							}
						}
					}
				}
			}
		}
	}
	public function showHelp($spacer = "") {
		global $wcSpecialTags;
		global $wcDefaults;
		echo "{$spacer}This tool adds tag '".self::$TagName."' to any comics with less than {$wcDefaults["FEWTAGS_LIMIT"]} tags.\n\n";
		echo "{$spacer}It requires no extra parameters.\n";
	}
	protected function loadOptions() {
		$this->_optionsLoaded = true;
	}
}
?>
